package com.sencorsta.ids.core.tcp.opensocket;

import com.sencorsta.ids.core.tcp.socket.server.RpcServerBootstrap;
import com.sencorsta.ids.core.tcp.websocket.SocketChooseHandle;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 对外服务端网络服务引导
 *
 * @author ICe
 */
public class OpenServerBootstrap extends RpcServerBootstrap {

    public final Map<String, OpenUser> users = new ConcurrentHashMap();
    public static final AttributeKey<OpenUser> KEY_OPENUSER = AttributeKey.valueOf("KEY_OPENUSER");


    private static OpenServerBootstrap instance;

    private OpenSender openSender;

    public static OpenServerBootstrap getInstance() {
        if (instance == null) {
            instance = new OpenServerBootstrap();
        }
        return instance;
    }


    public OpenServerBootstrap() {
        super("Open", new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                //pipeline.addLast("active",channelActiveHandler);
                //Socket 连接心跳检测
                pipeline.addLast("idleHandler", new OpenIdleStateHandler());
                pipeline.addLast("socketChoose",new SocketChooseHandle());

                //注意，这个专门针对 Socket 信息的解码器只能放在 SocketChooseHandler 之后，否则会导致 webSocket 连接出错
                pipeline.addLast("decoder",new OpenDecoder());
                pipeline.addLast("encoder", new OpenEncoder());
                //pipeline.addLast("handler",new OpenChannelHandler());

                pipeline.addLast("commonhandler",new OpenChannelHandler());



//                pipeline.addLast("idleHandler", new OpenIdleStateHandler());
//                pipeline.addLast("decoder", new OpenDecoder());
//                pipeline.addLast("encoder", new OpenEncoder());
//                pipeline.addLast("handler", new OpenChannelHandler());
            }
        });
        super.hostStr = "openServer.host";
        super.minPortStr = "openServer.port.min";
        super.maxPortStr = "openServer.port.max";
        super.portStr = "openServer.port";
        super.hostPublicStr="openServer.host.public";
        openSender=new OpenSender();
        new Thread(openSender).start();

    }


    public void addMessage(OpenMessage msg){
        openSender.addSend(msg);
    }


}
